//
//  CTForgetPassWordVC.m
//  digitalCurrency
//
//  Created by 默认账户 on 2019/5/31.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CTForgetPassWordVC.h"
#import "MSRegisterCell.h"
#import "MSVerifyCell.h"
#import "MSPasswordCell.h"
#import "WMHTMLViewController.h"
#import "LoginNetManager.h"
#import "countryViewController.h"
#import "YLTabBarController.h"

@interface CTForgetPassWordVC ()
@property (nonatomic, strong) UIButton *commitBtn;

@property (nonatomic, strong) UITextField *loginTF;
@property (nonatomic, strong) UITextField *verifyTF;
@property (nonatomic, strong) UITextField *passwordTF;
@property (nonatomic, strong) UITextField *repasswordTF;

@property (nonatomic, strong) UIButton *countryBtn;

@property (nonatomic, strong) UIButton *weakVerityBtn;
@end

@implementation CTForgetPassWordVC
    
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSubview];
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 65;
    self.tableView.separatorColor = [UIColor whiteColor];

    [self.tableView registerClass:[MSRegisterCell class] forCellReuseIdentifier:@"registerCell"];
    [self.tableView registerClass:[MSVerifyCell class] forCellReuseIdentifier:@"verifyCell"];
    [self.tableView registerClass:[MSPasswordCell class] forCellReuseIdentifier:@"passwordCell"];
    
    [self.view addSubview:self.commitBtn];
    
}
    
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGFloat statusH = kStatusBarHeight;
    
    CGRect rect = self.view.frame;
    rect.size.height = 65*4;
    rect.origin.y    = statusH +168;
    self.tableView.frame = rect;
    
    __weak typeof(self)weakself = self;
    
    [self.commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.tableView.mas_bottom).offset(40);
        make.left.mas_equalTo(23);
        make.right.mas_equalTo(-23);
        make.height.mas_equalTo(44);
    }];
    
//    [ToolUtil view:self.commitBtn gradineViewOne:self.commitBtn.bounds colorOne:[UIColor colorWithHEX:maincolor] colorTwo:[UIColor colorWithHEX:mainGradientColor]];

    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
    
}
    
-(void)selectCountry {
    countryViewController *countryVC = [[countryViewController alloc]init];
    countryVC.hidesBottomBarWhenPushed=YES;
    countryVC.returnValueBlock = ^(countryModel *model){
        NSLog(@"zhName:%@",model.zhName);
        [self.countryBtn setTitle:[NSString stringWithFormat:@"+%@",model.areaCode] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:self.countryBtn.titleLabel.text forKey:@"countrycode"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    YLNavigationController *nav = [[YLNavigationController alloc] initWithRootViewController:countryVC];
    [self presentViewController:nav animated:YES completion:nil];
}
    
- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}
    
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}
    
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:{
            MSRegisterCell *cell = [MSRegisterCell createTableView:tableView];
            self.loginTF = cell.textField;
            self.countryBtn = cell.selectedCountryBtn;

            @weakify(self);
            [[cell.selectedCountryBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                @strongify(self);
//                [self selectCountry];
            }];
            return cell;
        }
        break;
        case 1:{
            MSVerifyCell *cell = [MSVerifyCell createTableView:tableView];
            self.verifyTF = cell.textField;
            
            if (indexPath.row == 1) {
                self.weakVerityBtn = cell.verifyBtn;
                [[cell.verifyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    [self captchaButton];
                }];
            }
            
            return cell;
        }
        break;
        case 2:
        case 3:{
            MSPasswordCell *cell = [MSPasswordCell createTableView:tableView];
            if (indexPath.row == 2) {
                self.passwordTF = cell.textField;
            }
            else {
                self.repasswordTF = cell.textField;
            }
            cell.editingBlock = ^(NSString * _Nonnull text,NSInteger textLength) {
                if (textLength >= 8) {
                    self.commitBtn.enabled = YES;
                }
                else {
                    self.commitBtn.enabled = NO;
                }
            };
            
            return cell;
        }
        break;
        default:
        break;
    }
    
    return nil;
}
    
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}
    
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    
    [self.view endEditing:YES];
}
    
    
#pragma mark - CaptchaButtonDelegate
- (void)captchaButton {
    
    if (![NSString stringIsNull:self.loginTF.text]) {
        [self getphonncode];
    }
    else {
        [self.view makeToast:LocalizationKey(@"inputMobile") duration:1.5 position:CSToastPositionCenter];
    }
}
    
    //获取手机验证码
-(void)getphonncode {
    [self.view endEditing:YES];
    NSString *phoneNumber = self.loginTF.text;
    if (![NSString stringIsNull:phoneNumber]) {
        [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
        __block NSMutableString *postResult = [[NSMutableString alloc] init];
        NSDictionary *result = @{@"geetest_challenge": @"null",
                                 @"geetest_validate": @"null",
                                 @"geetest_seccode": @"null"
                                 };
        [result enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL * stop) {
            [postResult appendFormat:@"%@=%@&",key,obj];
        }];
        [postResult appendFormat:@"%@", [NSString stringWithFormat:@"phone=%@&area=%@",phoneNumber,@"86"]];
        NSDictionary *headerFields = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=UTF-8"};
        NSMutableURLRequest *secondaryRequest;
        secondaryRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,@"sendPhoneMassage"]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0];
        secondaryRequest.HTTPMethod = @"POST";
        secondaryRequest.allHTTPHeaderFields = headerFields;
        secondaryRequest.HTTPBody = [postResult dataUsingEncoding:NSUTF8StringEncoding];
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:secondaryRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [EasyShowLodingView hidenLoding];
            });
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (!error && httpResponse.statusCode == 200) {
                NSError *err;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
                if (!err) {
                    if ([dict[@"code"] integerValue] == 0) {
                        //发送验证码成功
                        __block int timeout=60; //倒计时时间
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                        dispatch_source_set_event_handler(_timer, ^{
                            if(timeout<=0){ //倒计时结束，关闭
                                dispatch_source_cancel(_timer);
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self.weakVerityBtn setTitle:LocalizationKey(@"sendValidate") forState:UIControlStateNormal];
                                    self.weakVerityBtn.userInteractionEnabled = YES;
                                });
                            }else{
                                int seconds = timeout % 90;
                                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self.weakVerityBtn setTitle: [NSString stringWithFormat:@"%@s",strTime] forState:UIControlStateNormal];
                                    self.weakVerityBtn.userInteractionEnabled = NO;
                                });
                                timeout--;
                            }
                        });
                        dispatch_resume(_timer);
                        
                    }
                    else {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [APPLICATION.window makeToast:dict[@"message"] duration:1.5 position:CSToastPositionCenter];
                        });
                        
                    }
                }
            }
        }];
        
        [task resume];
    }
    else {
        [self.view makeToast:LocalizationKey(@"inputMobile") duration:1.5 position:CSToastPositionCenter];
    }
}
    
#pragma mark-手机号码注册
- (void)commitRegister
    {
        NSString *verify = self.verifyTF.text;
        NSString *passwd = self.passwordTF.text;
        NSString *login  = self.loginTF.text;
        NSString *repasswordTF = self.repasswordTF.text;

        if ([NSString stringIsNull:login]) {
            [self.view makeToast:LocalizationKey(@"inputMobile") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        if ([NSString stringIsNull:verify]) {
            [self.view makeToast:LocalizationKey(@"inputCode") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        if ([NSString stringIsNull:passwd]) {
            [self.view makeToast:LocalizationKey(@"inputPwd") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        if (![ToolUtil matchPassword:passwd]) {
            [self.view makeToast:LocalizationKey(@"Enter a password combining 8-20 digits and letters") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        if ([NSString stringIsNull:repasswordTF]) {
            [self.view makeToast:LocalizationKey(@"inputPwd") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        if (![ToolUtil matchPassword:repasswordTF]) {
            [self.view makeToast:LocalizationKey(@"Enter a password combining 8-20 digits and letters") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        
        if (![repasswordTF isEqualToString:passwd]) {
            [self.view makeToast:LocalizationKey(@"Password error") duration:1.5 position:CSToastPositionCenter];
            return;
        }
        
        [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
        [LoginNetManager FogetToResetPasswordWithaccount:login withcode:verify withMode:0 Withpassword:passwd CompleteHandle:^(id resPonseObj, int code) {
            [EasyShowLodingView hidenLoding];
            if (code) {
                if ([resPonseObj[@"code"] integerValue] == 0) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
                else {
                    [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
                }
            }
            else{
                [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
            }
        }];
    }
    
- (UIButton *)commitBtn {
    if (!_commitBtn) {
        _commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitBtn.layer.cornerRadius  = 5.0;
        _commitBtn.layer.masksToBounds = YES;
        _commitBtn.backgroundColor     = [UIColor colorWithHEX:maincolor];
        
        [_commitBtn setTitle:LocalizationKey(@"Submit") forState:UIControlStateNormal];
        [_commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_commitBtn addTarget:self action:@selector(commitRegister) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _commitBtn;
}
    
- (void)addSubview {
    UIImage *img = [UIImage imageNamed:@"goback"];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:img forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kStatusBarHeight + 10);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(img.size.width);
        make.height.mas_equalTo(img.size.height);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:LocalizationKey(@"Forget password") attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size:36],NSForegroundColorAttributeName: tThreeColor}];
    label.attributedText = string;
    [self.view addSubview:label];
    CGFloat statusH = kStatusBarHeight;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(statusH + 69);
        make.left.mas_equalTo(33);
    }];
    
    UILabel *leftTitleLB = [[UILabel alloc]init];
    [self.view addSubview:leftTitleLB];
    [leftTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_left);
        make.top.equalTo(label.mas_bottom).offset(16);
    }];
    leftTitleLB.font = kFont(15);
    leftTitleLB.textColor = tSixColor;
    leftTitleLB.text = LocalizationKey(@"当前仅支持手机号找回密码");
}

@end
